/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-06-03 17:28:43
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-06-04 18:26:12
 * @Description : todoListStore
 */
import { defineStore, acceptHMRUpdate } from 'pinia'

export type Todo = {
  id?: string
  title: string
  completed: boolean
}

export type TotoListState = {
  todoList: Todo[]
}

export const useTodoListStore = defineStore('todoListStore', {
  state: (): TotoListState => {
    return {
      todoList: [],
    }
  },
  getters: {
    todoSize: (state) => {
      return state.todoList.length
    },
    completed: (state) => state.todoList.filter((todo) => todo.completed),
  },
  actions: {
    addTodo(todo: Todo) {
      // NOTE 不通过this.state.todoList
      if (!todo.id) todo.id = Math.random().toString(36)
      this.todoList.push(todo)
    },
    toggleTodo(id: string, completed?: boolean) {
      const arr = this.todoList.map((todo) => {
        if (todo.id !== id) return todo
        todo.completed = completed ?? !todo.completed
        return todo
      })
      this.todoList = arr
    },
  },
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useTodoListStore, import.meta.hot))
}
